package com.jacky.ws.endpoints;

import com.jacky.ws.config.AnnotationWebSocketConfig;
import jakarta.annotation.Resource;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

@Component
@ServerEndpoint(value = "/endpoint/{userIdentify}", configurator = AnnotationWebSocketConfig.class)
public class AnnotationServerEndpoint {


    private final Logger LOG = LoggerFactory.getLogger(AnnotationServerEndpoint.class);

    @OnOpen
    public void onOpen(Session session, @PathParam("userIdentify") String identify) {
        LOG.info("userIdentify:{}", identify);
        // 这里是从请求头获取到 Authorization
        Object authorization = session.getUserProperties().get("Authorization");
        if (Objects.isNull(authorization)) {
            throw new RuntimeException("auth fail");
        }
        CustomerSessionManager.addSession(session, identify);
    }

    @OnClose
    public void onClose(Session session, @PathParam("userIdentify") String identify) {
        LOG.info("onClose identify:{}", identify);
        CustomerSessionManager.removeSession(session);
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        for (Session s : CustomerSessionManager.getSessionList()) {
            if (s.equals(session)) continue;
            s.getBasicRemote().sendText(message);
        }
    }

    @OnError
    public void onError(Throwable error, Session session) {
        LOG.error("endpoint cause error:", error);
    }
}
